#!/usr/bin/python
import socket
import struct
import logging

#process args
loglevel = 'WARNING'
for st in sys.argv[1:]:
    if st.startswith('--log='):
        loglevel = st.split('=')[1]

#initialize logging
numeric_level = getattr(logging, loglevel.upper(), None)
if not isinstance(numeric_level, int):
    raise ValueError('Invalid log level: %s' % loglevel)
logging.basicConfig(level=numeric_level, format='%(levelname)s:%(message)s')

#get this node id
this_node_id = socket.gethostbyname(socket.gethostname())

#grab list of source/destination nodes
f = open('node_ips', 'r')   
node_list_temp = f.read().split('\n')[0:int(sys.argv[1])]
UDP_IPS = [socket.gethostbyname(x) for x in node_list_temp]
f.close()

sock = socket.socket(socket.AF_INET, # Internet
                     socket.SOCK_DGRAM) # UDP

#for each source, initiate a new session
for ip in UDP_IPS:
    temp_dest_list = [socket.inet_aton(x) for x in UDP_IPS where not ip != x]
    msg = '7' + socket.inet_aton(this_node_id) + struct.pack('=' + str(4*len(temp_dest_list)) + 's', ''.join(temp_dest_list))
    sock.sendto(msg, (ip, 50007))
    
    data, addr = sock.recvfrom(8)#ack
    
    print 'Session initiated on node: ' + ip
    